<template>
  <div id="login-container">
    <video
      class="video"
      src="../../assets/video/bg-video.mp4"
      preload="auto"
      loop="loop"
      autoplay="true"
      muted="muted"
    ></video>
    <div class="bg2"></div>
    <el-form
      :model="loginForm"
      status-icon
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="login-loginForm"
    >
      <h1 class="title">管理系统</h1>
      <i
        @click="iserweidenglu"
        :class="[
          'iconfont',
          'jiaobiao',
          isErweiLogin ? 'icon-diannaojiaobiao' : 'icon-erweimajiaobiao',
        ]"
      ></i>
      <!-- 切换标签 -->
      <div class="tab" v-show="!isErweiLogin">
        <span class="s1" @click="mimadenglu">密码登陆</span><span class="s2" @click="shoujidenglu">手机登陆</span>
      </div>
      <!-- 用户账号密码登陆 -->
      <div class="commonLogin" v-if="!isErweiLogin" v-show="isMMdenglu">
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="captcha">
          <el-input
            v-model="loginForm.captcha"
            @keydown.native.enter="submitForm('loginForm')"
            maxlength="5"
            ref="captcha"
          ></el-input>
          <div class="captcha-svg" v-html="captchaSvg" @click="updateCaptcha"></div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')">提交</el-button>
        </el-form-item>
      </div>
      <!-- 切换二维码登陆 -->
      <div class="erwei" v-else>
        <div class="erweibox">
          <i class="mask iconfont icon-saomachenggong-01" v-show="isSaomaSucced"></i>
          <i
            class="mask iconfont icon-erweima_shixiao"
            v-show="isErweiShixiao"
            @click="reloadEWM"
          ></i>
          <div class="erweiimg">
            <img :src="[erweimaurl]" style="height: 200px; width: 200px" />
          </div>
          <p v-text="saomaMsg"></p>
        </div>
      </div>
      <!-- 切换手机短信登陆 -->
      <div class="phoneLogin" v-show="isPhonedenglu">
        <div class="phonebox">
          <el-input v-model="phoneNumber" placeholder="请输入手机号" class="gsjh"></el-input>
          <el-row class="gyzm">
            <el-button type="success" plain @click="getyzm">获取验证码</el-button>
          </el-row>
          <el-input v-model="phoneyzm" placeholder="请输入验证码" class="syzm" @keydown.native.enter="denglu"></el-input>
          <el-row class="dl">
            <el-button type="success" plain @click="denglu">登陆</el-button>
          </el-row>
        </div>
      </div>
    </el-form>
  </div>
</template>
<script>
import * as api from "../../api";
import { mapMutations } from "vuex";
import io from "socket.io-client";
import qrcode from "qrcode";
var validateCaptcha = (rule, value, callback) => {
  //callback()只要传参就表示验证不通过，不传参表示验证通过
  //value就是input输入的值
  //rule是一个验证对象
  if (value.length != 5) {
    callback("必须输入5位验证码");
  } else {
    callback();
  }
};
var validateUsername = (rule, value, callback) => {
  var reg = /^\w{3,12}$/;
  if (reg.test(value)) {
    callback();
  } else {
    callback("用户名可以使字母数字下划线3-12位");
  }
};
var validatePass = (rule, value, callback) => {
  if (value.length < 3) {
    callback("密码长度不能小于3");
  } else {
    callback();
  }
};
export default {
  data() {
    return {
      isMMdenglu:true,
      isPhonedenglu:false,
      phoneNumber: "",
      phoneyzm: "",
      saomaMsg: "请使用手机微信扫码登陆",
      wechatCode: "",
      isSaomaSucced: false,
      isErweiShixiao: false,
      sidval: "",
      erweimaurl: "",
      isErweiLogin: false,
      loginForm: {
        username: "",
        password: "",
        captcha: "",
      },
      captchaSvg: "", //验证码的svg图片
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.updateCaptcha();
  },
  watch: {
    //监听切换状态
    isErweiLogin(newval, oldval) {
      if (newval) {
        //结果为true表示已经切换成了二维码登陆
        //1.通过socket.io和服务器建立连接
        let socket = io("wss://chst.vip");
        //2.监听socket连接成功事件，成功后发送请求"/users/getQrcode"获取登陆二维码地址
        socket.on("connectSuccess", (data) => {
          this.sidval = data.sid;
          api.getQrcodeUrlApi(this.sidval).then((res) => {
            let erweimahttp = res.data.scanCodeUrl;
            //3.通过qrcode插件将二维码地址生成二维码展示
            qrcode.toDataURL(erweimahttp, (err, dataURL) => {
              this.erweimaurl = dataURL;
            });
          });
          //4.用户扫描二维码
          //5.监听socket事件   scancodeSuccess(这是一个前后端约定事件) 获取wechatCode
          socket.on("scancodeSuccess", (res) => {
            this.isSaomaSucced = true;
            console.log(res);
            this.wechatCode = res.wechatCode;
            this.saomaMsg = res.msg;
            //6.请求/users/wechatLogin，传递wechatcode
            api
              .wechatLoginApi(this.wechatCode)
              .then((res) => {
                console.log(res);
                if (res.data.state) {
                  localStorage.setItem("qf-token", res.data.token);
                  localStorage.setItem("qf-userInfo", JSON.stringify(res.data.userInfo));
                  //保存用户信息到vuex
                  this.SET_USER_INFO(res.data.userInfo);
                  //存权限
                  localStorage.setItem(
                    "permissionButtons",
                    JSON.stringify(res.data.permission.buttons)
                  );
                  //跳转页面
                  this.$router.push("/");
                } else {
                  this.$message.error("微信登陆失败");
                }
              })
              .catch((res) => {
                this.$message.error("微信登陆失败");
              });
          });
          //7.判断失败  监听socket事件   invalidCode(这是一个前后端约定事件)
          socket.on("invalidCode", (res) => {
            console.log(res.state);
            if (res.state == false) {
              this.isErweiShixiao = true;
              this.saomaMsg = res.msg + "请点击刷新";
            }
          });
        });
      }
    },
  },
  methods: {
    iserweidenglu(){
      this.isErweiLogin = !this.isErweiLogin
      if(this.isErweiLogin){
        this.isPhonedenglu = false
        this.isMMdenglu = false
      }else{
        this.isPhonedenglu = false
        this.isMMdenglu = true
      }
    },
    shoujidenglu(){
      this.isPhonedenglu = true
      this.isMMdenglu = false
    },
    mimadenglu(){
      this.isMMdenglu = true
      this.isPhonedenglu = false
    },
    getyzm() {
      //获取验证码
      api.getPhoneloginYZApi(this.phoneNumber).then((res) => {
        console.log(res);
      });
    },
    denglu() {
      //手机验证码登陆
      api.phoneloginApi(this.phoneyzm).then((res) => {
        console.log(res);
        if (res.data.state) {
          //验证成功
          this.$message({
            showClose: true,
            message: "登陆成功",
            type: "success",
            duration: 1000,
          });
            //1.将token和userInfo存到本地, 并将用户信息添加到vuex
            //2.跳转主页
          localStorage.setItem("qf-token", res.data.token);
          localStorage.setItem("qf-userInfo", JSON.stringify(res.data.userInfo));
          //存权限,注意要传json字符串
          localStorage.setItem(
            "permissionButtons",
            JSON.stringify(res.data.permission.buttons)
          );
          this.$router.push("/");
          this.SET_USER_INFO(res.data.userInfo);
        } else {
          this.$message({
            showClose: true,
            message: "验证码错误",
            type: "error",
          });
        }
      });
    },
    ...mapMutations(["SET_USER_INFO"]),
    //获取验证码
    async updateCaptcha() {
      await api.getCaptchaApi().then((res) => {
        this.captchaSvg = res.data.img;
      });
    },
    submitForm(loginForm) {
      //console.log(this.$refs[formName])
      this.$refs[loginForm].validate((valid) => {
        //表示所有的表单校验通过之后valid的值时true
        //否则就是false
        if (valid) {
          //此时打开loading动画
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          //校验验证码
          api.verifyCaptcha(this.loginForm.captcha.toLowerCase()).then((res) => {
            if (res.data.state) {
              //验证码成功验证
              //继续验证同户名和密码
              api
                .loginApi(this.loginForm.username, this.loginForm.password)
                .then((res) => {
                  if (res.data.state) {
                    //登陆成功
                    //1.将token和userInfo存到本地, 并将用户信息添加到vuex
                    //2.跳转主页
                    this.$message({
                      showClose: true,
                      message: "登陆成功",
                      type: "success",
                      duration: 1000,
                    });
                    localStorage.setItem("qf-token", res.data.token);
                    localStorage.setItem(
                      "qf-userInfo",
                      JSON.stringify(res.data.userInfo)
                    );
                    //存权限,注意要传json字符串
                    localStorage.setItem(
                      "permissionButtons",
                      JSON.stringify(res.data.permission.buttons)
                    );
                    loading.close();
                    this.$router.push("/");
                    this.SET_USER_INFO(res.data.userInfo);
                  } else {
                    //登陆失败
                    loading.close();
                    this.$message({
                      showClose: true,
                      message: "账号或者密码错了哦",
                      type: "error",
                    });
                  }
                });
            } else {
              loading.close();
              //刷新验证码
              this.updateCaptcha();
              //清空验证码输入内容
              this.loginForm.captcha = "";
              //输入框获得焦点
              this.$refs.captcha.focus();
              this.$message({
                showClose: true,
                message: "验证码错了哦",
                type: "error",
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    reloadEWM() {
      console.log("点了");
      api.getQrcodeUrlApi(this.sidval).then((res) => {
        let erweimahttp = res.data.scanCodeUrl;
        //3.通过qrcode插件将二维码地址生成二维码展示
        qrcode.toDataURL(erweimahttp, (err, dataURL) => {
          this.erweimaurl = dataURL;
        });
      });
      this.saomaMsg = "请使用手机微信扫码登陆";
      this.isErweiShixiao = false;
    },
  },
};
</script>
<style scoped lang="less">
#login-container {
  .tab{
    color:white;
    font-size:18px;
    position:absolute;
    top:160px;
    left:120px;
    .s1{
      margin-right:10px;
      cursor:pointer;
    }
    .s2{
      margin-left:10px;
      cursor:pointer;
    }
  }
  .jiaobiao {
    font-size: 60px;
    color: #fff;
    position: absolute;
    right: 0px;
    top: 0px;
    cursor: pointer;
    opacity: 0.7;
  }
  .video {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
  }
  .bg2 {
    background: url(../../assets/img/bg2.png) no-repeat;
    position: fixed;
    height: 40%;
    width: 20%;
    background-size: 100% 100%;
    top: 40%;
    left: 20%;
    opacity: 0.5;
  }
  .el-form {
    position: fixed;
    left: 65%;
    top: 25%;
    border-radius: 5px;
    width: 400px;
    background-color: rgba(0, 0, 0, 0.3);
    padding: 100px 26px 50px 0;
    /deep/.el-input__inner {
      width: 250px;
    }
    /deep/.el-button--primary {
      background: linear-gradient(90deg, #1596fb, #002dff);
      width: 250px;
    }
    /deep/.el-form-item__label {
      color: #fff;
    }
    /deep/.el-form-item__content {
      .el-input {
        .el-input__inner {
          padding-right: 120px;
        }
      }
      .captcha-svg {
        background: #fff;
        height: 38px;
        width: 100px;
        position: absolute;
        right: 60px;
        bottom: 1px;
        cursor: pointer;
        svg {
          height: 38px !important;
          width: 100px !important;
        }
      }
    }
  }
  .title {
    margin: 0 0 60px 0;
    text-align: center;
    color: #fff;
  }
  /deep/.erwei {
    height: 248px;
    .erweibox {
      width: 200px;
      margin: 0 0 0 112px;
      p {
        text-align: center;
        color: white;
        font-weight: bold;
      }
      .icon-saomachenggong-01 {
        font-size: 100px;
        position: absolute;
        color: green;
        left: 160px;
        top: 250px;
      }
      .icon-erweima_shixiao {
        font-size: 100px;
        position: absolute;
        color: red;
        left: 160px;
        top: 250px;
        cursor: pointer;
      }
    }
  }
  .phoneLogin{
    padding-top:50px;
    .phonebox{
      height:200px;
      position: relative;
      .gsjh{
        position:absolute;
        left:50px;
        top:0;
        width:250px;
      }
      .syzm{
        position:absolute;
        left:50px;
        top:50px;
        width:250px;
      }
      .gyzm{
        position:absolute;
        right:50px;
        top:0;
      }
      .dl{
        position:absolute;
        right:50px;
        top:50px;
        .el-button--success{
          width:112px;
        }
      }
    }
  }
}
</style>
